import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, Modal, message as msg} from 'antd';
import {
    FORM_OPTIONS,
    TABLE,
    PAGINATION_OPTIONS,
    PAGE,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    ROWSELECTION_FIXED_COLUMN_WIDTH,
    DATE_FORMAT
} from '../constants';
import TextInput from 'Shared/components/TextInput';
import {conventSorter} from './utils';
import {formatAmount, conventEnumValueToString, formatDateTime} from '../utils';
import {getPartShipment} from './api';
import SelectAlert from '../common/SelectAlert';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import {partShipOrderStatus, partShipNoticeStatus, partShipmentStatus, transportType} from '../Enum';
import styles from './style.css';
const FormItem = Form.Item;
import moment from 'moment';
import {injectIntl, language} from './intl';

const partShipOrderStatusTolist = partShipOrderStatus.toList(language);
const partShipNoticeStatusTolist = partShipNoticeStatus.toList(language);
const partShipmentStatusTolist = partShipmentStatus.toList(language);
class PartShipmentSelectPanel extends PureComponent {
    state = {
        keys: [],
        rows: [],
        code: '',
        partInvoiceCode: '',
        invoicedDate: [],
        partShipOrderStatus: undefined,
        partShipNoticeStatus: undefined,
        partShipmentStatus: undefined,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        isFetching: false,
        data: {},
        message: '',
        currentCondition: {}
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        getPartShipment(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            partInvoiceCode: this.state.partInvoiceCode,
            invoicedDate: this.state.invoicedDate,
            partShipOrderStatus: this.state.partShipOrderStatus,
            partShipNoticeStatus: this.state.partShipNoticeStatus,
            partShipmentStatus: this.state.partShipmentStatus,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        const invoicedDate = (condition = {}) => {
            const {invoicedDate, ...others} = condition;
            if(!invoicedDate || invoicedDate.length === 0) return condition;
            return {
                ...others,
                beginInvoicedDate: moment(invoicedDate[0]).toISOString(),
                endInvoicedDate: moment(invoicedDate[1]).toISOString(),
            };
        };
        this.onQuery(invoicedDate(condition));
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onClickReset = () => {
        this.setState({
            code: '',
            partInvoiceCode: '',
            invoicedDate: [],
            partShipOrderStatus: undefined,
            partShipNoticeStatus: undefined,
            partShipmentStatus: undefined,
        });
    }
    onCloseTag = () => {
        this.setState({
            keys: [],
            rows: []
        });
    }
    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }
    onSubmit = () => {
        if(!this.state.rows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'partShipmentSelectPanel.validate.queryDealer',
                defaultMessage: '请选择发运订单'
            }));
        this.props.onSelect(this.state.rows[0]);
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.partInvoiceCode',
                    defaultMessage: '备件箱单发票编号'
                }),
                dataIndex: 'partInvoiceCode',
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.invoicedDate',
                    defaultMessage: '开票日期'
                }),
                dataIndex: 'invoicedDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.partShipOrderStatus',
                    defaultMessage: '委托书状态'
                }),
                dataIndex: 'partShipOrderStatus',
                render: text => conventEnumValueToString(partShipOrderStatus, text),
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.partShipNoticeStatus',
                    defaultMessage: '通知书状态'
                }),
                dataIndex: 'partShipNoticeStatus',
                render: text => conventEnumValueToString(partShipNoticeStatus, text),
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.partShipmentStatus',
                    defaultMessage: '状态'
                }),
                dataIndex: 'partShipmentStatus',
                render: text => conventEnumValueToString(partShipmentStatus, text),
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.shipmentType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'shipmentType',
                render: text => conventEnumValueToString(transportType, text),
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.origin',
                    defaultMessage: '起运地'
                }),
                dataIndex: 'origin',
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.destination',
                    defaultMessage: '目的地'
                }),
                dataIndex: 'destination',
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.carrierName',
                    defaultMessage: '货代名称'
                }),
                dataIndex: 'carrierName',
            },
            {
                title: formatMessage({
                    id: 'partShipmentSelectPanel.column.invoiceAmount',
                    defaultMessage: '发票金额'
                }),
                dataIndex: 'invoiceAmount',
                render: text => formatAmount(text)
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record);
            }
        });
        const rowSelection = {
            type: 'radio',
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.keys,
        };
        const selectRows = this.state.rows.length ? [{
            text: this.state.rows[0].code,
            value: this.state.rows[0].id
        }] : [];
        return (
            <Modal
                title={formatMessage({
                    id: 'partShipmentSelectPanel.show.dealerQuery',
                    defaultMessage: '发运订单查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partShipmentSelectPanel.show.code',
                            defaultMessage: '编号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="code"
                                value={this.state.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partShipmentSelectPanel.show.partInvoiceCode',
                            defaultMessage: '箱单发票编号'
                        })}
                        {...FORM_OPTIONS.item}>
                            <TextInput
                                name="partInvoiceCode"
                                value={this.state.partInvoiceCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partShipmentSelectPanel.show.invoicedDate',
                            defaultMessage: '开票日期'
                        })}
                        {...FORM_OPTIONS.item}>
                            <DateRangePicker
                                name="invoicedDate"
                                value={this.state.invoicedDate}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partShipmentSelectPanel.show.partShipOrderStatus',
                            defaultMessage: '委托书状态'
                        })}
                        {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="partShipOrderStatus"
                                options={partShipOrderStatusTolist}
                                value={this.state.partShipOrderStatus}
                                onChange={this.onChange}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partShipmentSelectPanel.show.partShipNoticeStatus',
                            defaultMessage: '通知书状态'
                        })}
                        {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="partShipNoticeStatus"
                                options={partShipNoticeStatusTolist}
                                value={this.state.partShipNoticeStatus}
                                onChange={this.onChange}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partShipmentSelectPanel.show.partShipmentStatus',
                            defaultMessage: '状态'
                        })}
                        {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="partShipmentStatus"
                                options={partShipmentStatusTolist}
                                value={this.state.partShipmentStatus}
                                onChange={this.onChange}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            className={styles.btnMargin}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'partShipmentSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'partShipmentSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <SelectAlert data={selectRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="partShipmentId"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    onRow={onRow}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }} />
            </Modal >
        );
    }
}

PartShipmentSelectPanel.propTypes = {
    intl: PropTypes.object,
    onCancel: PropTypes.func,
    onSelect: PropTypes.func,
};
import {connect} from 'react-redux';

export default connect(null, null)(injectIntl(PartShipmentSelectPanel));
